import api from './api.js';
//const Host = "http://192.168.2.148:8888"; //余佳测试服务器
//const Host = "http://192.168.2.148:8888"; //测试服务器
//const Host = "https://api.gaibailin.cn"; //正式服务器

var wxset_Data = {
    Host: "https://api.gaibailin.cn",//服务器地址
    openId: '', //用户与小程序唯一标识符
}

function Ajax(e, r, callback) { //网络请求

    var method = 'POST'; //请求方式
    if (typeof e === 'string') {
        method = e
    } else {
        callback = r;
        r = e;
    }

    var url = wxset_Data.Host + r[0]; //要请求的服务器地址

    wx.request({
        url: url,
        method: method,
        data: r[1],
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        success: (res) => {
            if (Array.isArray(callback)) {
                callback[0](res.data);
            } else {
                callback(res.data);
            }
        },
        fail: (res) => {
            if (callback[1]) {
                callback[1](res);
            } else {
                wx.showToast({
                    title: '服务器开了小差',
                    icon: 'none',
                    duration: 3000
                })
            }
        }
    })
}

//调起支付执行函数【e,必要参数.t执行回调】
function wxpay(e, t) {
    wx.requestPayment({
        'timeStamp': e.timeStamp,
        'nonceStr': e.nonceStr,
        'package': e.package,
        'signType': 'MD5',
        'paySign': e.sign,
        'success': function(res) {
            t(res)
        },
        'fail': function(res) {
            t(res)
        }
    })
}

function Login(callback, e) {
    wx.login({
        success: res => {
            var data = {
                wxcode: res.code
            }
            if (e) {
                Object.assign(data, e);
            } //将e对象合并到data中去
            Ajax([api.login, data, true], [(success) => {
                if (success.statusCode == 200) {
                    wxset_Data.userInfo.nickName = success.data.nickName; //用户昵称
                    wxset_Data.userInfo.avatarUrl = success.data.avatarUrl; //用户头像
                    wxset_Data.openId = success.data.openId
                } else {
                    wx.showToast({
                        title: 'openid获取失败',
                        icon: "none"
                    })
                }
                callback(success);
            }, (fail) => {
                wx.showToast({
                    title: 'openid获取失败',
                    icon: "none"
                })
                console.log(fail);
            }])
        }
    })
}

module.exports = {
    api,
    Ajax,
    Login,
    wxpay,
    wxset_Data,
    upimg: function(e, r, t) {
        wx.uploadFile({
            url: host + 'upload',
            filePath: e,
            name: 'file',
            success: (res) => {
                r(res)
            }
        })
    }
}